<template>
  <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    status-icon
    :rules="rules"
    label-width="auto"
    class="demo-ruleForm"
    label-position="left"
  >
    <el-form-item label="手机号" prop="telephone">
      <el-input v-model="ruleForm.telephone" clearable />
    </el-form-item>
    <el-form-item label="验证码" prop="smsCode">
      <el-input style="width: 100px" v-model="ruleForm.smsCode" clearable />
      <el-button
        class="sms-btn"
        type="primary"
        @click="sendSmsCode"
        :disabled="isSending || countdown > 0"
      >
        {{ isSending ? '发送中...' : countdown > 0 ? `${countdown}秒后重试` : '发送验证码' }}
      </el-button>
    </el-form-item>

    <el-form-item>
      <div class="form-button">
        <el-button type="primary" @click="submitForm(ruleFormRef)"> 登录 </el-button>
        <el-button @click="goToPwdForm">账号密码登录</el-button>
      </div>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { showErrorMsg } from '@/utils/alterMessage.js'
import { useLoginStore } from '@/stores/login/login.js'
import { storeToRefs } from 'pinia'

const loginStore = useLoginStore()
const { isSending, countdown, ruleForm } = storeToRefs(loginStore)

const ruleFormRef = ref()

const validateTel = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入手机号'))
  } else {
    // 假设有效的手机号为11位数字，且以1开头
    // /^1[3-9]\d{9}$/ /^1\d{10}$/
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(value)) {
      callback(new Error('请输入有效的手机号'))
    } else {
      callback()
    }
  }
}

const validateSmsCode = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入验证码'))
  } else if (value.length !== 6) {
    callback(new Error('验证码为6位字符'))
  } else {
    callback()
  }
}

const rules = reactive({
  telephone: [{ validator: validateTel, trigger: 'blur' }],
  smsCode: [{ validator: validateSmsCode, trigger: 'blur' }]
})

const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      loginStore.loginBySms()
    } else {
      showErrorMsg('请输入正确的手机号和密码')
    }
  })
}

const sendSmsCode = () => {
  // 验证手机号
  validateTel(null, ruleForm.value.telephone, (error) => {
    if (error) {
      // 显示错误信息
      showErrorMsg(error.message)
      return // 验证未通过，终止发送操作
    }

    // 手机号验证通过，继续发送验证码
    loginStore.sendSmsCode()
  })
}

const goToPwdForm = () => {
  window.location.href = '/login/TelAndPwdForm'
}
</script>

<style lang="scss" scoped>
.demo-ruleForm {
  .form-button {
    width: 100%;
    height: 100%;
    display: flex;
    margin-top: 20px;
    //均匀
    justify-content: space-between;
  }
  .sms-btn {
    margin-left: 20px;
    width: 80px;
    background-color: rgb(96 165 250);
  }
}
</style>
